package com.lbd.media.service.impl;

import com.lbd.base.service.BaseServiceImpl;
import com.lbd.commons.exception.ControllerException;
import com.lbd.media.bean.Media;
import com.lbd.media.dao.MediaRepository;
import com.lbd.media.service.MediaService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * Created by WangYajie on 2016/9/12.
 */
@Service
@Transactional
public class MediaServiceImpl extends BaseServiceImpl<Media, MediaRepository> implements MediaService {
    private final Logger log = Logger.getLogger(this.getClass());
    @Autowired
    MediaRepository mediaRepository;

    @Override
    public Specification<Media> getSpecification(Media media) {
        return null;
    }

    /**
     * 构建媒体查询信息和参数
     *
     * @param media
     * @param parameter(根据标题|创建着ID|媒体类型)
     * @return
     */
    @Override
    public String buildJpql(Media media, Map<String, Object> parameter) {
        StringBuilder jpqlBuilder = new StringBuilder("  from  Media t   ");
        if (media != null) {
            if (StringUtils.isNotBlank(media.getTitle())) {
                jpqlBuilder.append(" and  t.title like :title");
                parameter.put("title", "%" + media.getTitle() + "%");
            }
            if (StringUtils.isNotBlank(media.getState())) {
                jpqlBuilder.append(" and  t.state =:state");
                parameter.put("state", media.getState());
            }
            if (StringUtils.isNotBlank(media.getCategory())) {
                jpqlBuilder.append(" and  t.category like :category");
                parameter.put("category", "%" + media.getCategory() + "%");
            }
            jpqlBuilder.append(" order by createdDate desc ");
        }
        return jpqlBuilder.toString();
    }

    /**
     * 根据ID查询媒体类型
     *
     * @param id
     * @return
     */
    @Override
    public Media findById(String id) {
        return mediaRepository.findOne(id);
    }

    @Override
    public void update(Media media) {
        //校验已发布的不允许修改
        Media old = mediaRepository.findOne(media.getId());
        if ("01".equals(old.getState())) {//TODO 获取数据字典、校验数据（如old)
            throw new ControllerException("发布后不允许修改");
        }
        //复制创建信息
        media.setCreateUserId(old.getCreateUserId());
        media.setCreatedDate(old.getCreatedDate());
        super.update(media);
    }
}
